package main

import (
	"fmt"
	"time"
)

// 将函数作为参数
func main() {
	start := time.Now()
	callback(1, Add)
	f()
	//匿名函数 主函数内部 独立的函数内部自调用或用作参数
	func() {
		sum := 0
		for i := 1; i <= 100; i++ {
			sum += i
		}
		fmt.Println("sum:", sum)
	}()
	p2 := Add2()
	fmt.Println("p2:", p2(2))
	TwoADdder := Adder(2)
	fmt.Println("TwoADdder:", TwoADdder(2))
	fib1 := fib()
	for i := 0; i < 10; i++ {
		fmt.Println(fib1())
	}
	end := time.Now()
	fmt.Println("time:", end.Sub(start))

}

func Add(a, b int) int {
	fmt.Println("Add:", a, b, a+b)
	return a + b
}

func callback(y int, f func(a, b int) int) {
	f(y, 2)
}

// 具名函数

func f() {
	fmt.Println("Hello, Anonymous")
}

func Add2() func(b int) int {
	return func(b int) int {
		return b + 1
	}
}

func Adder(a int) func(b int) int {
	return func(b int) int {
		return a + b
	}
}

func fib() func() int {
	a, b := 0, 1
	return func() int {
		temp := a
		a, b = b, a+b
		return temp
	}
}
